import React, { useState, useEffect } from 'react';
import {
    Button,
    Cascader,
    Result,
    Form,
    Input,
    Alert,
    message,
    Select,
    Row,
    Col,
    Modal
} from 'antd';
import { Register } from '@/api/login';
import { history } from '@umijs/max';
import {
    ImportOutlined,
    CheckOutlined,
    SafetyOutlined
} from '@ant-design/icons';
const { Option } = Select;
import { ChinaMap } from '@/components/utils/ChinaMap'
import { GetCaptchaImg, PostCaptcha, PostEmailLink, PostEmailActive } from "@/api/login"


const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
    },
};

const tailFormItemLayout = {
    wrapperCol: {
        xs: {
            span: 24,
            offset: 0,
        },
        sm: {
            span: 16,
            offset: 8,
        },
    },
};


export default () => {
    const [form] = Form.useForm();
    const [addr, setAddr] = useState(ChinaMap) // 中国行政区域数据
    const [logo, setlogo] = useState(false)
    const [captchaSrc, setCaptchaSrc] = useState('/assets/img/captcha.png'); // 验证码图片的URL 
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [EmailLink, setEmailLink] = useState('')
    const [msg, setMsg] = useState({})
    const [isDisabled, setIsDisabled] = useState(false);
    const [countdown, setCountdown] = useState(0);
    const [timerId, setTimerId] = useState(null);
    // 清除定时器的函数  
    const clearTimer = () => {
        if (timerId) {
            clearInterval(timerId);
            setTimerId(null);
        }
    };

    // 倒计时逻辑  
    useEffect(() => {
        if (countdown > 0) {
            const id = setInterval(() => {
                setCountdown(prevCountdown => prevCountdown - 1);
            }, 1000);
            setTimerId(id);

            // 组件卸载或禁用状态改变时清除定时器  
            return () => clearTimer();
        } else {
            setCountdown(0)
            setIsDisabled(false)
            return () => clearTimer();
        }
    }, [countdown, isDisabled]);


    const prefixSelector = (
        <Form.Item name="prefix" noStyle>
            <Select style={{ width: 70 }}>
                <Option value="86">+86</Option>
                <Option value="87">+87</Option>
            </Select>
        </Form.Item>
    );
    // 背景图片
    const svg = '/assets/svg/bg.svg'
    // 组件初始化 时候运行
    const RegisterData = async (options) => {
        try {
            const data = await Register(options)
            // console.log(data)
            if (data.status === 200) {

                message.success('注册成功，即将跳转到登录界面')
                setIsModalOpen(false);
                setlogo(true)
                // history.push('/user/login');
            }
            if (data.status === 400) {
                message.error('该用户已存在')
            }
        } catch (err) {
            // console.log(err)
            message.error('注册异常')
        }
    }
    // 获取邮箱校验链接
    const GetEmailLink = async (email) => {
        try {
            const data = await PostEmailLink({ 'email': email })
            // console.log(data)
            if (data.status === 200) {
                // 禁用按钮并开始倒计时  
                setIsDisabled(true);
                setCountdown(60);
                message.success('链接发送成功，请到邮箱查收')
                return
            }
            message.error(data.message)
        } catch (err) {
            message.error('发送链接失败')
            // console.log(err)
        }
    }

    const handleClick = () => {
        if (!isDisabled) {
            GetEmailLink(EmailLink)
        }
    };
    const IsEmailActive = async (email) => {
        try {
            const data = await PostEmailActive({ 'email': email })
            // console.log(data)
            if (data.status === 200) {
                message.success(data.message)
                RegisterData(msg)
                return
            }
            message.error(data.message)
        } catch (err) {
            message.error('校验失败')
            console.log(err)
        }
    }
    const handleOk = () => {
        // console.log('wedf',msg)
        IsEmailActive(EmailLink)
        // setIsModalOpen(false);

    };
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    // 提交注册信息
    const onFinish = async (values: any) => {
        // console.log('Received values of form: ', values);
        try {
            const captchadata = await PostCaptcha({ 'captcha': values.captcha })
            if (captchadata.status !== 200) {
                message.error('图形验证码错误！')
                return
            }
            const { username, password, password2, addr = [''], tel = '', email = '' } = values
            setMsg({ username, password, password2, 'addr': addr.join(''), tel, email }) // 收集用户的注册信息
            if (email !== '') {
                setIsModalOpen(true)
                setEmailLink(email)
                return
            }
            RegisterData({ username, password, password2, 'addr': addr.join(''), tel, email })
        } catch (err) {
            console.log(err)

        }
    };
    // 获取验证码图片  
    const getCaptcha = async () => {
        try {
            const response = await GetCaptchaImg()
            const url = URL.createObjectURL(response)
            // console.log('url', url)
            setCaptchaSrc(url)
        } catch (err) {
            console.log(err)
            message.info('验证码获取失败')
        }
    }
    // 初次加载 初始化验证码图片  
    useEffect(() => {
        getCaptcha();
    }, []);
    return (
        <>
            <Modal title="注册邮箱校验" open={isModalOpen} onOk={handleOk} onCancel={handleCancel} okText="完成校验并提交注册" cancelText="取消校验" width={800} >
                <p>现在对邮箱地址：<span style={{ color: 'red' }}>{EmailLink}</span>进行校验工作~</p>
                {/* {isDisabled ? `${countdown}s后可再次发送` : '获取验证码'} */}
                <p>邮箱校验链接的有效期为 5分钟，收到后请尽快点击收到的邮箱链接，看到成功即是校验成功</p>
                <Button type="primary" onClick={handleClick} disabled={isDisabled}>
                    {isDisabled ? `${countdown}s后可再次发送` : '点击发送邮箱校验链接'}
                </Button>
            </Modal>
            <div style={{
                top: 0,
                left: 0,
                width: '100%',
                height: '100%',
                backgroundImage: `url(${svg})`,
                backgroundSize: 'cover',
                backgroundPosition: 'center'
            }}>
                {logo ? <Result
                    status="success"
                    title="恭喜您，注册账号成功!"
                    subTitle="尽快去登录界面，体验不一样的数据服务吧 ~"
                    extra={[
                        <Button type="primary" key="console" onClick={() => {
                            history.push('/user/login');
                        }}>
                            点击跳转登录页面
                        </Button>
                    ]}
                /> :
                    <Form
                        {...formItemLayout}
                        form={form}
                        name="register"
                        onFinish={onFinish}
                        initialValues={{ addr: ['广东省', '广州市', '海珠区'], prefix: '86' }}
                        style={{ maxWidth: 800, margin: '60px auto' }}
                        scrollToFirstError
                    >
                        <Alert message="佳立数据服务中心 新用户注册中心：" style={{ fontSize: '18px', fontWeight: '600' }} />
                        <Form.Item label="基础信息填写：">
                            <span className="ant-form-text"></span>
                        </Form.Item>
                        <Form.Item
                            name="username"
                            label="用户名"
                            extra={<>
                                必填；长度为150个字符或以下；只能包含字母、数字、特殊字符“@”、“.”、“-”和“_”。<br></br>
                                <span style={{ fontWeight: '600' }}>用户名必须是唯一的，不得跟其他人的用户名产生冲突</span>
                            </>}
                            tooltip="为自己设置一个用户名?"
                            rules={[{ required: true, message: '请输入您的注册用户名!', whitespace: true }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            name="password"
                            label="设置您的密码"
                            extra={<>
                                你的密码不能与你的其他个人信息太相似。<br />
                                你的密码必须包含至少 8 个字符。<br />
                                你的密码不能是一个常见密码。<br />
                                你的密码不能全都是数字。
                            </>}
                            rules={[
                                {
                                    required: true,
                                    message: '请输入密码！',
                                },
                                {
                                    min: 8,
                                    message: '密码必须至少包含8个字符！',
                                },
                                ({ getFieldValue }) => ({
                                    validator(_, value) {
                                        if (value && /^\d+$/.test(value)) {
                                            return Promise.reject(new Error('密码不能是纯数字！'));
                                        }
                                        return Promise.resolve();
                                    },
                                }),
                            ]}
                            hasFeedback
                        >
                            <Input.Password />
                        </Form.Item>

                        <Form.Item
                            name="password2"
                            label="密码确认"
                            extra="为了校验，请输入与上面相同的密码。"
                            dependencies={['password']}
                            hasFeedback
                            rules={[
                                {
                                    required: true,
                                    message: '请再次输入密码!',
                                },
                                ({ getFieldValue }) => ({
                                    validator(_, value) {
                                        if (!value || getFieldValue('password') === value) {
                                            return Promise.resolve();
                                        }
                                        return Promise.reject(new Error('两次输入的密码不一致!'));
                                    },
                                }),
                            ]}
                        >
                            <Input.Password />
                        </Form.Item>
                        <Form.Item
                            name="addr"
                            label="个人地址"
                            rules={[
                                { type: 'array', required: false, message: '请填写您的个人地址' },
                            ]}
                        >
                            <Cascader options={addr} />
                        </Form.Item>
                        <Form.Item
                            name="email"
                            label="邮箱地址"
                            rules={[
                                {
                                    type: 'email',
                                    message: '邮箱格式不正确！',
                                },
                                {
                                    required: true,
                                    message: '此项为必填，填写后需要进行邮箱校验，校验通过才能注册（可用于邮箱地址登录）',
                                },
                            ]}
                        >
                            <Input placeholder="此项为必填，填写后需要进行邮箱校验，校验通过才能注册（可用于邮箱验证登录）" />
                        </Form.Item>
                        <Form.Item
                            name="tel"
                            label="手机号码"
                            rules={[
                                {
                                    required: false,
                                    message: '请填写您的手机号',
                                },
                                {
                                    pattern: /^1[3-9]\d{9}$/,
                                    message: '手机号码格式不正确',
                                },
                            ]}
                        >
                            <Input addonBefore={prefixSelector} style={{ width: '100%' }} />
                        </Form.Item>
                        <Form.Item
                            extra={<span style={{ 'color': 'rgb(143 177 232)' }}>如若验证码不清晰，点击验证码刷新</span>}
                            name="captcha"
                            label="验证码"
                            // noStyle
                            rules={[{ required: true, message: '请填写验证码信息!' },
                            { pattern: /^[0-9a-zA-Z]{4}$/, message: '验证码必须是四个字符长度，且只能包含数字和字母!' },
                            ]}
                        >
                            <Row gutter={8}>
                                <Col span={13}>
                                    <Input size="large" prefix={<SafetyOutlined />} placeholder="图形验证码" maxLength={4} />
                                </Col>
                                <Col span={9} offset={2}>
                                    <a><img src={captchaSrc} style={{ height: '100%' }} onClick={getCaptcha} /></a>
                                </Col>
                            </Row>
                        </Form.Item>
                        <Form.Item {...tailFormItemLayout}>
                            <Button type="primary" htmlType="submit" icon={<CheckOutlined />}>
                                提交注册信息
                            </Button>
                            <Button type="primary" onClick={() => {
                                history.push('/user/login');
                            }} style={{ marginLeft: '100px' }} danger icon={<ImportOutlined />}>
                                已有账户?  跳转到登录界面
                            </Button>
                        </Form.Item>
                    </Form>

                }
            </div >
        </>
    )
}